function [share_d, profit_d] = get_share(x, N_d, alpha_constant, xi_d, alpha_price, alpha_population, population_log_d, alpha_distance, distance_d, q_0, delta_market, index_d, alpha_1, Y_d, FE_d, alpha_FE, nn, expmu_market, Y_market, price_k_market, q_k_market, prod_pct_d)

price_d = x(1:N_d, 1); 
q_d = x((N_d + 1):(2*N_d), 1); 
mc_d = x((2*N_d + 1):(3*N_d), 1);
m1_d_1 = x(end, 1); 

m1_d = ones(N_d, 1) * m1_d_1;


delta_d = alpha_constant + xi_d + log(price_d)*alpha_price + alpha_population*population_log_d + alpha_distance*distance_d + (q_d - q_0);
delta_market_counter = delta_market;
delta_market_counter = delta_market_counter(index_d == 0, 1);
delta_market_counter = [delta_market_counter; delta_d];
expmeanval_market_counter = exp(delta_market_counter);

expmu_d = exp(log(price_d)*alpha_1*Y_d + repmat(FE_d*alpha_FE,1,nn));
expmu_market_counter = expmu_market;
expmu_market_counter = expmu_market_counter(index_d == 0, :);
expmu_market_counter = [expmu_market_counter; expmu_d];

marketForProducts_counter = ones(size(delta_market_counter,1), 1);
sharesum_market_counter = sparse(zeros(1,size(delta_market_counter,1)));
sharesum_market_counter(1,:) = 1;
oo = ones(1,nn);   
numer_counter = (expmeanval_market_counter*oo ).*expmu_market_counter;        
sum1 = sharesum_market_counter*numer_counter;
sum11 = 1./(0+sum1);                      
denom1 = sum11(marketForProducts_counter,:);    
simShare_counter = numer_counter.*denom1;              
EstShare_counter = mean(simShare_counter,2); 
share_d = EstShare_counter((end - N_d + 1):end);

sum_s = simShare_counter;
sum_s2 = simShare_counter.^2;
alpha_i = alpha_price + alpha_1*Y_market;
sum_alpha_s = alpha_i.*simShare_counter;
sum_alpha_s2 = alpha_i.*(simShare_counter.^2);
sum_s = sum_s((end - N_d + 1):end,:);
sum_s2 = sum_s2((end - N_d + 1):end,:);
sum_alpha_s = sum_alpha_s((end - N_d + 1):end,:);
sum_alpha_s2 = sum_alpha_s2((end - N_d + 1):end,:);

obj1 = share_d .* mc_d + (price_d - mc_d) .* (1/nn) .* [sum(sum_alpha_s,2) - sum(sum_alpha_s2,2)];   
obj2 = - m1_d .* (log(mc_d) ./ q_d) .* share_d + ((price_d - mc_d) ./ mc_d) .* (1/nn) .* [sum(sum_s,2) - sum(sum_s2,2)];   
obj3 = sum(share_d .* price_d)/sum(share_d) - price_k_market(index_d,1);
obj4 = sum(share_d .* q_d)/sum(share_d) - q_k_market(index_d,1);
obj5 = share_d - prod_pct_d * share_d(1,1);


obj = [obj1; obj2; obj3; obj4; obj5];

profit_d = ((price_d - mc_d) ./ price_d) .* share_d;

end

